import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../data/models/album.dart';
import '../../../domain/providers/backup_provider.dart';

/// 相册项组件
class AlbumItem extends StatelessWidget {
  /// 相册数据
  final Album album;

  /// 选择状态变更回调
  final ValueChanged<bool> onSelectionChanged;

  const AlbumItem({
    Key? key,
    required this.album,
    required this.onSelectionChanged,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final backupProvider = Provider.of<BackupProvider>(context);
    final autoBackupPhotos = backupProvider.autoBackupPhotos;
    final autoBackupVideos = backupProvider.autoBackupVideos;

    // 根据开关状态显示有效项目数
    final effectiveCount = album.getEffectiveCount(
      autoBackupPhotos: autoBackupPhotos,
      autoBackupVideos: autoBackupVideos,
    );

    // 根据开关状态构建小标题
    final String subtitle = _buildSubtitle(
      autoBackupPhotos: autoBackupPhotos,
      autoBackupVideos: autoBackupVideos,
    );

    return ListTile(
      leading: _buildThumbnail(),
      title: Text(album.name),
      subtitle: Text(subtitle),
      trailing: Switch(
        value: album.isSelected,
        onChanged: onSelectionChanged,
        activeColor: Colors.blue,
      ),
    );
  }

  /// 构建缩略图
  Widget _buildThumbnail() {
    return Container(
      width: 48,
      height: 48,
      decoration: BoxDecoration(
        color: Colors.grey.shade300,
        borderRadius: BorderRadius.circular(4),
      ),
      child:
          album.thumbnailData != null
              ? ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Image.memory(album.thumbnailData!, fit: BoxFit.cover),
              )
              : _buildPlaceholderIcon(),
    );
  }

  /// 构建占位图标
  Widget _buildPlaceholderIcon() {
    IconData iconData;
    // 根据相册名称选择图标
    final lowerName = album.name.toLowerCase();
    if (lowerName.contains('camera') || lowerName.contains('相机')) {
      iconData = Icons.camera_alt;
    } else if (lowerName.contains('screenshot') || lowerName.contains('截图')) {
      iconData = Icons.screenshot;
    } else {
      iconData = Icons.image;
    }

    return Center(child: Icon(iconData, color: Colors.grey));
  }

  /// 构建子标题
  String _buildSubtitle({
    required bool autoBackupPhotos,
    required bool autoBackupVideos,
  }) {
    final StringBuffer buffer = StringBuffer('共');

    if (autoBackupPhotos && autoBackupVideos) {
      // 显示总数
      buffer.write('${album.totalCount}项');

      if (album.photoCount > 0 && album.videoCount > 0) {
        buffer.write(' (${album.photoCount}照片, ${album.videoCount}视频)');
      }
    } else if (autoBackupPhotos) {
      // 只显示照片数量
      buffer.write('${album.photoCount}张照片');
    } else if (autoBackupVideos) {
      // 只显示视频数量
      buffer.write('${album.videoCount}个视频');
    } else {
      // 都没开，显示总数
      buffer.write('${album.totalCount}项');
    }

    return buffer.toString();
  }
}
